<?php
/**
 * 用户管理
 * @since   2018-06-11
 * @author  winljm001 <winljm001@126.com>
 */

namespace app\admin\controller;



use app\model\AdminSubject;
use app\util\ReturnCode;
use app\util\Tools;

class Subject extends Base {

    /**
     * 获取题目列表
     * @return array
     * @throws \think\exception\DbException
     * @author  winljm001 <winljm001@126.com>
     */
    public function index() {

        $limit = $this->request->get('size', config('apiAdmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $keywords = $this->request->get('keywords', '');
        $type = $this->request->get('type', '');
        $level = $this->request->get('level', '');
        $status = $this->request->get('status', '');

        $where = [];
        if ($status === '1' || $status === '0') {
            $where['status'] = $status;
        }
        if ($type!='') {
            $where['type'] = $type;
        }
        if ($level!='') {
            $where['level'] = $level;
        }
        
        if($keywords!=''){
            $where=array_merge($where,['id|question'=>['like', "%{$keywords}%"]]);
        }

        $listObj = (new AdminSubject())->where($where)->order('updateTime DESC')
            ->paginate($limit, false, ['page' => $start])->toArray();
        $listInfo = $listObj['data'];
        return $this->buildSuccess([
            'list'  => $listInfo,
            'count' => $listObj['total']
        ]);
    }

    /**
     * 新增题目
     * @return array
     * @author  winljm001 <winljm001@126.com>
     */
    public function add() {
        $postData = $this->request->post();
        $postData['addTime'] = time();
        $postData['updateTime'] = time();
        $res = AdminSubject::create($postData);
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
        } else {
            return $this->buildSuccess([]);
        }
    }

    /**
     * 删除题目
     * @return array
     * @author winljm001 <winljm001@126.com>
     */
    public function del() {
        $id = $this->request->get('id');
        if (!$id) {
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS, '缺少必要参数');
        }
        AdminSubject::destroy($id);
        return $this->buildSuccess([]);
    }

    /**
     * 获取题目
     * @return object
     * @author winljm001 <winljm001@126.com>
     */
    public function getDetail() {
        $id = $this->request->get('id');
        if (!$id) {
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS, '缺少必要参数');
        }
        $data = AdminSubject::get(['id' => $id]);
        return $this->buildSuccess([
            'subject'  => $data
        ]);
    }

    /**
     * 获取随机题目列表
     * @return object
     * @author winljm001 <winljm001@126.com>
     */
    public function getRandomSubject() {

        $num = $this->request->get('num', 5);//需要抽取的默认条数
        $level = $this->request->get('level', '');
        $type = $this->request->get('type', '');
        $where=[];
        if ($type!='') {
            $where['type'] = $type;
        }
        if ($level!='') {
            $where['level'] = $level;
        }
        $pk = (new AdminSubject())->getPK();//获取主键
        $countcus = (new AdminSubject())->where($where)->field($pk)->select();//查询数据
        if(count($countcus)<$num){
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '题目不够');
        }
        $con = '';
        $qu = '';
        foreach($countcus as $v=>$val){
            $con.= $val[$pk].'|';
        }
        $array = explode("|",$con);
        $countnum = count($array)-1;
        $randomArr=[];
        do{
            $sunum = mt_rand(0,($countnum-1));
            $flag=false;
            foreach ($randomArr as $key => $value) {
                if($value==$sunum){
                    $flag=true;
                }
            }
            if($flag){
                continue;
            }
            $qu.= $array[$sunum].',';
            $randomArr[]=$sunum;
        }while(count($randomArr)<$num);
        $list = (new AdminSubject())->where($pk,'in',$qu)->select();
        return $this->buildSuccess([
            'list'  => $list
        ]);
    }
    /**
     * 编辑题目
     * @author winljm001 <winljm001@126.com>
     * @return array
     * @throws \think\exception\DbException
     */
    public function edit() {
        $postData = $this->request->post();
        $postData['updateTime'] = time();
        $res = AdminSubject::update($postData);
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
        } else {
            return $this->buildSuccess([]);
        }
    }

    /**
     * 题目状态编辑
     * @return array
     * @author winljm001 <winljm001@126.com>
     */
    public function changeStatus() {
        $idArr = explode(',',$this->request->get('id'));
        if ($idArr[0]== '') {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '缺少必要参数');
        }
        $status = $this->request->get('status');
        foreach ($idArr as $key => $value) {
            $res = AdminSubject::update([
                'Id'         => $value,
                'status'     => $status
            ]);
        }
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
        } else {
            return $this->buildSuccess([]);
        }
    }

    /**
     * 获取总题目数量
     * @return object
     * @author winljm001 <winljm001@126.com>
     */
    public function getSubjectNum() {
        $num=count((new AdminSubject())->select());
        return $this->buildSuccess([
            'subjectNum'  => $num
        ]);
    }
    
    /**
     * 获取总题目类型
     * @return array
     * @author winljm001 <winljm001@126.com>
     */
    public function getAllSubjectType() {
        $arr=(new AdminSubject())->field('type')->select();
        return $this->buildSuccess([
            'subjectType'  => $arr
        ]);
    }

    /**
     * 题目上传Excel
     * @return array
     * @author winljm001 <winljm001@126.com>
     */
    public function uploadExcel() {
        if(request()->isPost()){
            if (!empty($_FILES)){
                import('PHPExcel.PHPExcel', EXTEND_PATH);
                $PHPExcel = new \PHPExcel();
                $file = request()->file('file');  
                $info = $file->validate(['size'=>15678,'ext'=>'xlsx,xls,csv'])->move(ROOT_PATH . 'Uploads' . DS . 'Excel');
                if($info){
                    $exclePath = $info->getSaveName();  //获取文件名  
                    $file_name = ROOT_PATH . 'Uploads' . DS . 'Excel' . DS . $exclePath;   //上传文件的地址
                    $objReader =\PHPExcel_IOFactory::createReader('Excel2007'); 
                    $obj_PHPExcel =$objReader->load($file_name, $encode = 'utf-8');  //加载文件内容,编码utf-8  
                    $excel_array=$obj_PHPExcel->getsheet(0)->toArray();   //转换为数组格式  
                    array_shift($excel_array);  //删除第一个数组(标题); 
                    $i=0;
                    $data = array();
                    for($i = 0; $i < count($excel_array); $i++){
                        $data[]  = [
                            'type' => $excel_array[$i][0],           
                            'question' => $excel_array[$i][1],          
                            'option' => $excel_array[$i][2],         
                            'answer' => $excel_array[$i][3],
                            'analysis' => $excel_array[$i][4],
                            'knowledgePoint' => $excel_array[$i][5],
                            'status' => $excel_array[$i][6],
                            'level'=>$excel_array[$i][7],
                            'addTime'=>time(),
                            'updateTime'=>time()
                        ] ;
                    }
                    $result   =AdminSubject::insertAll($data); 
                    if($result){
                        return $this->buildSuccess([]);
                    }  else{
                        return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
                    }
                } else{
                     // 上传失败获取错误信息  
                    return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
                }
            }else {
                return $this->fetch();
            }
        }else{
            return $this->fetch();
        }
    }
}
